// xx-ai 文件浏览器 JavaScript

$(document).ready(function() {
    // 初始化工具提示
    initializeTooltips();
    
    // 初始化键盘快捷键
    initializeKeyboardShortcuts();
    
    // 初始化文件路径输入框
    initializePathInput();
    
    // 初始化表格功能
    initializeTableFeatures();
    
    // 初始化文件上传功能
    initializeFileUpload();
    
    // 初始化拖拽上传
    initializeDragDropUpload();
    
    // 初始化IP地址显示功能
    initializeIpAddressDisplay();
});

/**
 * 初始化工具提示
 */
function initializeTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

/**
 * 初始化键盘快捷键
 */
function initializeKeyboardShortcuts() {
    $(document).on('keydown', function(event) {
        // Alt + H: 返回首页
        if (event.altKey && event.key === 'h') {
            event.preventDefault();
            window.location.href = '/file/';
        }
        
        // Alt + U: 上级目录
        if (event.altKey && event.key === 'u') {
            event.preventDefault();
            const parentLink = $('a[href*="parentPath"]');
            if (parentLink.length > 0) {
                parentLink.click();
            }
        }
        
        // Ctrl + F: 聚焦搜索框
        if (event.ctrlKey && event.key === 'f') {
            event.preventDefault();
            const pathInput = $('input[name="path"]');
            if (pathInput.length > 0) {
                pathInput.focus();
                pathInput.select();
            }
        }
    });
}

/**
 * 初始化路径输入框功能
 */
function initializePathInput() {
    const pathInput = $('input[name="path"]');
    if (pathInput.length > 0) {
        // 添加输入验证
        pathInput.on('input', function() {
            validatePath($(this).val());
        });
        
        // 添加自动完成功能（简单版本）
        pathInput.on('keydown', function(event) {
            if (event.key === 'Tab') {
                // 这里可以添加路径自动完成逻辑
                // 目前只是简单的阻止默认行为
            }
        });
    }
}

/**
 * 验证路径
 */
function validatePath(path) {
    const pathInput = $('input[name="path"]');
    if (pathInput.length === 0) return;
    
    // 简单的路径验证
    const isValid = path && path.trim().length > 0 && !path.includes('..');
    
    if (isValid) {
        pathInput.removeClass('is-invalid').addClass('is-valid');
    } else {
        pathInput.removeClass('is-valid').addClass('is-invalid');
    }
}

/**
 * 初始化表格功能
 */
function initializeTableFeatures() {
    // 添加行点击事件
    $('.file-directory, .file-item').on('click', function(event) {
        // 如果点击的是链接，不处理
        if ($(event.target).is('a')) {
            return;
        }
        
        // 如果是目录行，点击整行都可以导航
        const link = $(this).find('a');
        if (link.length > 0) {
            link.click();
        }
    });
    
    // 添加鼠标悬停效果
    $('.file-directory, .file-item').on('mouseenter', function() {
        const link = $(this).find('a');
        $(this).css('cursor', link.length > 0 ? 'pointer' : 'default');
    });
}

/**
 * 显示加载状态
 */
function showLoading(button) {
    if (button) {
        const $button = $(button);
        const originalHtml = $button.html();
        $button.html('<span class="loading"></span> 加载中...');
        $button.prop('disabled', true);
        
        // 存储原始内容以便恢复
        $button.data('originalHtml', originalHtml);
    }
}

/**
 * 隐藏加载状态
 */
function hideLoading(button) {
    if (button && $(button).data('originalHtml')) {
        const $button = $(button);
        $button.html($button.data('originalHtml'));
        $button.prop('disabled', false);
        $button.removeData('originalHtml');
    }
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

/**
 * 复制路径到剪贴板
 */
function copyPathToClipboard(path) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(path).then(function() {
            showToast('路径已复制到剪贴板', 'success');
        }).catch(function() {
            showToast('复制失败', 'error');
        });
    } else {
        // 回退方法
        const textArea = $('<textarea>').val(path);
        $('body').append(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            showToast('路径已复制到剪贴板', 'success');
        } catch (err) {
            showToast('复制失败', 'error');
        }
        textArea.remove();
    }
}

/**
 * 显示提示消息
 */
function showToast(message, type = 'info') {
    // 创建 toast 容器（如果不存在）
    let toastContainer = document.querySelector('.toast-container');
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.className = 'toast-container position-fixed top-0 end-0 p-3';
        toastContainer.style.zIndex = '9999';
        document.body.appendChild(toastContainer);
    }
    
    const toastId = 'toast-' + Date.now();
    const toastHtml = `
        <div id="${toastId}" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <i class="bi bi-${getToastIcon(type)} text-${type} me-2"></i>
                <strong class="me-auto">提示</strong>
                <button type="button" class="btn-close" data-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;
    
    toastContainer.insertAdjacentHTML('beforeend', toastHtml);
    
    // 初始化并显示 toast
    const toastElement = document.getElementById(toastId);
    const toast = new bootstrap.Toast(toastElement, {
        delay: 3000
    });
    toast.show();
    
    // 自动清理
    toastElement.addEventListener('hidden.bs.toast', function() {
        toastElement.remove();
    });
}

/**
 * 获取 toast 图标
 */
function getToastIcon(type) {
    const icons = {
        'success': 'check-circle',
        'error': 'exclamation-circle',
        'warning': 'exclamation-triangle',
        'info': 'info-circle'
    };
    return icons[type] || icons['info'];
}

/**
 * API 调用函数
 */
const FileAPI = {
    /**
     * 浏览目录
     */
    browseDirectory: function(path, options = {}) {
        const params = new URLSearchParams({
            path: path,
            showHidden: options.showHidden || false,
            sortBy: options.sortBy || 'name',
            sortOrder: options.sortOrder || 'asc'
        });
        
        return fetch(`/file/api/browse?${params}`)
            .then(response => response.json())
            .catch(error => {
                console.error('API调用失败:', error);
                throw error;
            });
    },
    
    /**
     * 重命名文件或目录
     */
    renameFile: function(oldPath, newName) {
        const params = new URLSearchParams({
            oldPath: oldPath,
            newName: newName
        });
        
        return fetch('/file/api/rename', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        })
        .then(response => {
            if (response.ok) {
                return response.text();
            } else {
                throw new Error('重命名失败');
            }
        })
        .catch(error => {
            console.error('重命名API调用失败:', error);
            throw error;
        });
    }
};

/**
 * 工具函数
 */
const Utils = {
    /**
     * 防抖函数
     */
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    /**
     * 节流函数
     */
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
};

// 导出到全局作用域（如果需要）
window.FileAPI = FileAPI;
window.Utils = Utils;

// ================ 文件上传下载功能 ================

/**
 * 初始化文件上传功能
 */
function initializeFileUpload() {
    const fileInput = $('#file');
    const uploadForm = $('#uploadForm');
    
    if (fileInput.length > 0) {
        // 文件选择变化事件
        fileInput.on('change', function(e) {
            handleFileSelection(e.target.files);
            validateUploadForm();
        });
    }
    
    if (uploadForm.length > 0) {
        // 表单提交事件
        uploadForm.on('submit', function(e) {
            handleUploadSubmit(e);
        });
    }
}

/**
 * 初始化拖拽上传功能
 */
function initializeDragDropUpload() {
    const uploadArea = $('.upload-area');
    const fileInput = $('#file');
    
    if (uploadArea.length === 0 || fileInput.length === 0) {
        return;
    }
    
    // 防止默认拖拽行为
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        uploadArea.on(eventName, preventDefaults);
        $(document).on(eventName, preventDefaults);
    });
    
    // 拖拽时高亮显示
    ['dragenter', 'dragover'].forEach(eventName => {
        uploadArea.on(eventName, highlight);
    });
    
    // 拖拽离开时取消高亮
    ['dragleave', 'drop'].forEach(eventName => {
        uploadArea.on(eventName, unhighlight);
    });
    
    // 处理文件放置
    uploadArea.on('drop', handleDrop);
    
    // 点击上传区域触发文件选择
    uploadArea.on('click', function() {
        fileInput.click();
    });
    
    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }
    
    function highlight(e) {
        uploadArea.addClass('dragover');
    }
    
    function unhighlight(e) {
        uploadArea.removeClass('dragover');
    }
    
    function handleDrop(e) {
        const dt = e.originalEvent.dataTransfer;
        const files = dt.files;
        
        fileInput[0].files = files;
        handleFileSelection(files);
        validateUploadForm();
    }
}

/**
 * 处理文件选择
 */
function handleFileSelection(files) {
    const fileInfo = $('#fileInfo');
    const fileList = $('#fileList');
    
    if (fileInfo.length === 0 || fileList.length === 0) {
        return;
    }
    
    if (files.length > 0) {
        fileInfo.removeClass('d-none');
        fileList.empty();
        
        let totalSize = 0;
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            totalSize += file.size;
            
            const fileItem = createFileItem(file, i);
            fileList.append(fileItem);
        }
        
        // 添加总计信息
        const totalInfo = $('<div>').addClass('mt-2 pt-2 border-top').html(`
            <strong>总计：${files.length} 个文件，${formatFileSize(totalSize)}</strong>
        `);
        fileList.append(totalInfo);
    } else {
        fileInfo.addClass('d-none');
    }
}

/**
 * 创建文件项目元素
 */
function createFileItem(file, index) {
    const fileItem = $('<div>').addClass('file-item-upload');
    
    const fileIcon = getFileIcon(file.name, file.type);
    const fileTypeText = file.type || '未知类型';
    const isValidSize = file.size <= 1024 * 1024 * 1024; // 1024MB
    
    fileItem.html(`
        <div class="file-info">
            <div class="file-details">
                <div class="file-icon">
                    <i class="${fileIcon}"></i>
                </div>
                <div>
                    <div class="file-name">${escapeHtml(file.name)}</div>
                    <div class="file-size ${isValidSize ? 'text-muted' : 'text-danger'}">
                        ${formatFileSize(file.size)}
                        ${isValidSize ? '' : ' (超出1024MB限制)'}
                    </div>
                </div>
            </div>
            <div class="file-actions">
                <span class="badge bg-secondary">${fileTypeText}</span>
                <button type="button" class="btn btn-outline-danger btn-sm" 
                        onclick="removeFileItem(${index})" title="移除">
                    <i class="bi bi-x"></i>
                </button>
            </div>
        </div>
    `);
    
    return fileItem;
}

/**
 * 移除文件项目
 */
function removeFileItem(index) {
    const fileInput = $('#file');
    if (fileInput.length === 0 || !fileInput[0].files) {
        return;
    }
    
    // 创建新的FileList（移除指定索引的文件）
    const dt = new DataTransfer();
    const files = Array.from(fileInput[0].files);
    
    files.forEach((file, i) => {
        if (i !== index) {
            dt.items.add(file);
        }
    });
    
    fileInput[0].files = dt.files;
    handleFileSelection(fileInput[0].files);
    validateUploadForm();
}

/**
 * 验证上传表单
 */
function validateUploadForm() {
    const fileInput = $('#file');
    const uploadBtn = $('#uploadBtn');
    const targetPath = $('#targetPath');
    
    if (fileInput.length === 0 || uploadBtn.length === 0 || targetPath.length === 0) {
        return;
    }
    
    const files = fileInput[0].files;
    const hasFiles = files && files.length > 0;
    const hasValidPath = targetPath.val().trim().length > 0;
    const allFilesValid = hasFiles && Array.from(files).every(file => file.size <= 1024 * 1024 * 1024);
    
    uploadBtn.prop('disabled', !hasFiles || !hasValidPath || !allFilesValid);
}

/**
 * 处理上传表单提交
 */
function handleUploadSubmit(e) {
    const fileInput = $('#file');
    const files = fileInput[0].files;
    
    if (!files || files.length === 0) {
        e.preventDefault();
        showToast('请选择要上传的文件', 'warning');
        return;
    }
    
    // 检查文件大小
    const maxSize = 1024 * 1024 * 1024; // 1024MB
    for (let i = 0; i < files.length; i++) {
        if (files[i].size > maxSize) {
            e.preventDefault();
            showToast(`文件 "${files[i].name}" 超过1024MB限制`, 'error');
            return;
        }
    }
    
    // 显示上传进度
    showUploadProgress();
}

/**
 * 显示上传进度
 */
function showUploadProgress() {
    const uploadBtn = $('#uploadBtn');
    const progressCard = $('#uploadProgress');
    const statusDiv = $('#uploadStatus');
    
    if (uploadBtn.length > 0) {
        uploadBtn.prop('disabled', true);
        uploadBtn.html('<i class="bi bi-cloud-upload"></i> 上传中...');
    }
    
    if (progressCard.length > 0) {
        progressCard.removeClass('d-none');
    }
    
    if (statusDiv.length > 0) {
        statusDiv.text('正在上传文件...');
    }
    
    // 模拟进度（实际项目中应该使用真实的上传进度）
    simulateUploadProgress();
}

/**
 * 模拟上传进度
 */
function simulateUploadProgress() {
    const progressBar = $('#progressBar');
    const statusDiv = $('#uploadStatus');
    
    if (progressBar.length === 0) {
        return;
    }
    
    let progress = 0;
    const interval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress >= 95) {
            progress = 95;
            clearInterval(interval);
            if (statusDiv.length > 0) {
                statusDiv.text('即将完成...');
            }
        }
        
        progressBar.css('width', progress + '%');
        progressBar.text(Math.round(progress) + '%');
    }, 300);
}

/**
 * 获取文件图标
 */
function getFileIcon(fileName, fileType) {
    const extension = getFileExtension(fileName).toLowerCase();
    
    // 图片文件
    if (/^image\//.test(fileType) || ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'].includes(extension)) {
        return 'bi bi-file-image file-icon-image';
    }
    
    // 文档文件
    if (['pdf', 'doc', 'docx', 'txt', 'rtf'].includes(extension)) {
        return 'bi bi-file-text file-icon-document';
    }
    
    // 压缩文件
    if (['zip', 'rar', '7z', 'tar', 'gz'].includes(extension)) {
        return 'bi bi-file-zip file-icon-archive';
    }
    
    // 视频文件
    if (/^video\//.test(fileType) || ['mp4', 'avi', 'mkv', 'mov', 'wmv'].includes(extension)) {
        return 'bi bi-file-play file-icon-video';
    }
    
    // 音频文件
    if (/^audio\//.test(fileType) || ['mp3', 'wav', 'flac', 'aac'].includes(extension)) {
        return 'bi bi-file-music file-icon-audio';
    }
    
    // 代码文件
    if (['js', 'css', 'html', 'java', 'py', 'cpp', 'c', 'h'].includes(extension)) {
        return 'bi bi-file-code file-icon-code';
    }
    
    // 默认文件
    return 'bi bi-file-earmark file-icon-default';
}

/**
 * 获取文件扩展名
 */
function getFileExtension(fileName) {
    if (!fileName) {
        return '';
    }
    
    const lastDotIndex = fileName.lastIndexOf('.');
    if (lastDotIndex > 0 && lastDotIndex < fileName.length - 1) {
        return fileName.substring(lastDotIndex + 1);
    }
    
    return '';
}

/**
 * HTML转义
 */
function escapeHtml(text) {
    const div = $('<div>').text(text);
    return div.html();
}

/**
 * 下载文件
 */
function downloadFile(filePath, inline = false) {
    const url = `/file/download?path=${encodeURIComponent(filePath)}&inline=${inline}`;
    
    if (inline) {
        // 在新窗口中打开
        window.open(url, '_blank');
    } else {
        // 使用隐藏的a标签下载，避免意外的页面跳转
        const link = $('<a>').attr('href', url).css('display', 'none').attr('download', '');
        $('body').append(link);
        link[0].click();
        link.remove();
        
        console.log('下载文件:', filePath);
    }
}

/**
 * 删除文件（API方式）
 */
function deleteFileApi(filePath) {
    if (!confirm('确定要删除这个文件吗？该操作不可恢复！')) {
        return;
    }
    
    fetch('/file/api/delete', {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `filePath=${encodeURIComponent(filePath)}`
    })
    .then(response => response.text())
    .then(data => {
        if (response.ok) {
            showToast(data, 'success');
            // 刷新页面
            window.location.reload();
        } else {
            showToast(data, 'error');
        }
    })
    .catch(error => {
        showToast('删除文件时发生错误', 'error');
        console.error('Error:', error);
    });
}

/**
 * 上传文件（API方式）
 */
function uploadFileApi(formData, onProgress) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        // 上传进度
        if (onProgress) {
            xhr.upload.addEventListener('progress', (e) => {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    onProgress(percentComplete);
                }
            });
        }
        
        // 完成事件
        xhr.addEventListener('load', () => {
            if (xhr.status === 200) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    resolve(response);
                } catch (e) {
                    reject(new Error('解析响应失败'));
                }
            } else {
                reject(new Error(`上传失败: ${xhr.status}`));
            }
        });
        
        // 错误事件
        xhr.addEventListener('error', () => {
            reject(new Error('网络错误'));
        });
        
        // 发送请求
        xhr.open('POST', '/file/api/upload');
        xhr.send(formData);
    });
}

// 扩展FileAPI
FileAPI.downloadFile = downloadFile;
FileAPI.deleteFile = deleteFileApi;
FileAPI.uploadFile = uploadFileApi;

// 扩展Utils
Utils.formatFileSize = formatFileSize;
Utils.getFileIcon = getFileIcon;
Utils.escapeHtml = escapeHtml;

// ================ IP地址获取功能 ================

/**
 * 初始化IP地址显示功能
 */
function initializeIpAddressDisplay() {
    const showIpBtn = $('#showIpAddressesBtn');
    const modal = $('#ipAddressesModal');
    const ipListContainer = $('#ipAddressesList');
    const copyAllBtn = $('#copyAllAddressesBtn');
    
    if (showIpBtn.length > 0) {
        // 点击按钮显示模态框
        showIpBtn.on('click', function() {
            // 显示加载状态
            ipListContainer.html(`
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在获取IP地址信息...</p>
            `);
            
            // 显示模态框 - 使用Bootstrap的modal方法
            $('#ipAddressesModal').modal('show');
            
            // 获取IP地址信息
            getLocalIpAddresses();
        });
    }
    
    if (copyAllBtn.length > 0) {
        // 复制所有地址按钮事件
        copyAllBtn.on('click', function() {
            copyAllIpAddresses();
        });
    }
    
    // 确保模态框可以正确关闭
    modal.on('hidden.bs.modal', function () {
        // 清理可能存在的定时器或其他资源
        console.log('模态框已关闭');
    });
}

/**
 * 获取本地IP地址
 */
function getLocalIpAddresses() {
    const ipListContainer = $('#ipAddressesList');
    
    // 显示加载状态
    ipListContainer.html(`
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
        </div>
        <p class="mt-2">正在获取IP地址信息...</p>
    `);
    
    // 通过AJAX调用后端API获取IP地址信息
    $.ajax({
        url: '/file/api/ip-addresses',
        method: 'GET',
        dataType: 'json',
        timeout: 10000, // 10秒超时
        success: function(data) {
            if (data.success && data.addresses) {
                displayIpAddresses(data.addresses);
            } else {
                handleIpError(new Error(data.message || '获取IP地址信息失败'));
            }
        },
        error: function(xhr, status, error) {
            handleIpError(new Error('网络请求失败: ' + error));
        }
    });
}

/**
 * 处理IP获取错误
 */
function handleIpError(error) {
    const ipListContainer = $('#ipAddressesList');
    ipListContainer.html(`
        <div class="alert alert-warning" role="alert">
            <i class="bi bi-exclamation-triangle"></i>
            无法获取IP地址信息: ${error.message}
        </div>
        <div class="mt-3">
            <h6>您可以尝试以下地址访问：</h6>
            <ul class="list-group">
                <li class="list-group-item">
                    <div class="d-flex justify-content-between">
                        <div>
                            <strong>本地回环地址 (IPv4)</strong>
                            <div class="text-muted small">仅本机访问</div>
                        </div>
                        <div class="text-break">
                            <a href="${window.location.protocol}//127.0.0.1${window.location.port ? ':' + window.location.port : ''}/file/" 
                               target="_blank">${window.location.protocol}//127.0.0.1${window.location.port ? ':' + window.location.port : ''}/file/</a>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    `);
}

/**
 * 显示IP地址列表
 */
function displayIpAddresses(addresses) {
    const ipListContainer = $('#ipAddressesList');
    let html = '<ul class="list-group">';
    
    addresses.forEach(addr => {
        html += `
            <li class="list-group-item">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <strong>${addr.name} (${addr.type})</strong>
                        <div class="text-muted small">点击复制或直接访问</div>
                    </div>
                    <div class="d-flex align-items-center">
                        <button class="btn btn-outline-primary btn-sm me-2 copy-btn" data-url="${addr.url}">
                            <i class="bi bi-clipboard"></i>
                        </button>
                        <a href="${addr.url}" target="_blank" class="btn btn-outline-success btn-sm">
                            <i class="bi bi-box-arrow-up-right"></i>
                        </a>
                    </div>
                </div>
                <div class="mt-2 text-break bg-light p-2 rounded">
                    <code>${addr.url}</code>
                </div>
            </li>
        `;
    });
    
    html += '</ul>';
    ipListContainer.html(html);
    
    // 绑定复制按钮事件
    $('.copy-btn').on('click', function() {
        const url = $(this).data('url');
        copyToClipboard(url, $(this));
    });
}

/**
 * 复制文本到剪贴板
 */
function copyToClipboard(text, buttonElement) {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            // 显示成功提示
            if (buttonElement) {
                const originalHtml = buttonElement.html();
                buttonElement.html('<i class="bi bi-check"></i>');
                setTimeout(() => {
                    buttonElement.html(originalHtml);
                }, 2000);
            }
            showToast('地址已复制到剪贴板', 'success');
        }).catch(() => {
            showToast('复制失败', 'error');
        });
    } else {
        // 回退方法
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        try {
            document.execCommand('copy');
            // 显示成功提示
            if (buttonElement) {
                const originalHtml = buttonElement.html();
                buttonElement.html('<i class="bi bi-check"></i>');
                setTimeout(() => {
                    buttonElement.html(originalHtml);
                }, 2000);
            }
            showToast('地址已复制到剪贴板', 'success');
        } catch (err) {
            showToast('复制失败', 'error');
        }
        document.body.removeChild(textArea);
    }
}

/**
 * 复制所有IP地址
 */
function copyAllIpAddresses() {
    const addresses = [];
    $('.list-group-item').each(function() {
        const url = $(this).find('code').text();
        if (url) {
            addresses.push(url);
        }
    });
    
    if (addresses.length > 0) {
        const text = addresses.join('\n');
        copyToClipboard(text, $('#copyAllAddressesBtn'));
    } else {
        showToast('没有可复制的地址', 'warning');
    }
}
